package com.niuke.binarysearchsorting;

/**
 * 二分查找
 */
public class BinarySearchTest01 {
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     *
     * @param nums int整型一维数组
     * @param target int整型
     * @return int整型
     */
    public int search (int[] nums, int target) {
        // write code here
        //1.判断数组是否为空，如果为空，返回-1
        if(nums.length == 0 || nums.length >= 10000){
            return -1;
        }
        //2.判断数组中元素的值是否都在[-9999,9999]之间，如果不在也都返回-1
//        for (int i = 0; i < nums.length; i++) {
//            if(nums[i] < -9999 || nums[i] > 9999){
//                return -1;
//            }
//        }
        int start = 0;
        int end = nums.length - 1;
        int mid = 0;
        for (int i = start; i <= end; i ++){
            mid = (start + end) / 2;
            if(nums[mid] < target){
                start = mid + 1;
            }
            else if(nums[mid] > target){
                end = mid - 1;
            }
            else{
                return mid;
            }
        }
        return -1;
    }

    //写一个测试方法
    public static void main(String[] args){
        BinarySearchTest01 binarySearchTest01 = new BinarySearchTest01();
        int[] nums = {9999};
        int target = 9999;
        int search = binarySearchTest01.search(nums, target);
        System.out.println("给定的元素所在数组下标的位置为:" + search);
    }
}
